/**
 * @author xiao zhou
 * @lastEditTime 2021-06-10 15:29:59
 * @description
 */

const fs = require('fs')
const archiver = require('archiver')
const { log, succeed, error, underline } = require('../utils')

module.exports = async (config, index) => {
  await new Promise((resolve, reject) => {
    log(`(${index}) 压缩 ${underline(config.distPath)} Zip`)
    const archive = archiver('zip', { 'zlib': { 'level': 9 } }).on('error', e => {
      error(e)
    })
    const output = fs
      // eslint-disable-next-line no-undef
      .createWriteStream(`${process.cwd()}/${config.distPath}.zip`)
      .on('close', e => {
        if (e) {
          error(`打包zip出错: ${e}`)
          reject(e)
          // eslint-disable-next-line no-undef
          process.exit(1)
        } else {
          succeed(`${underline(`${config.distPath}.zip`)} 压缩成功`)
          resolve()
        }
      })

    archive.pipe(output)
    archive.directory(config.distPath, false)
    archive.finalize()
  })
}
